
 
using Simulation.Framework;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace Easy.Game2d
{
    public static class DataManager
    {
        public static Config config { get; private set; }
        private static List<LoadDataHandler> handlers;

        public static void Init()
        {
            handlers = new List<LoadDataHandler>();
            handlers.Add(LoadConfigData);
        }

        public static void Clear()
        {
            ClearConfigData();
 
            handlers?.Clear();
            handlers = null;
        }

        public static void LoadData(UnityAction onComplete)
        {
            int index = 0;

            UnityAction action = () => {
                index++;
                if (index >= handlers.Count)
                    onComplete?.Invoke();
            };

            for (int i = 0; i < handlers.Count; i++)
                handlers[i].Invoke(action);
        }

        #region config

        private static void LoadConfigData(UnityAction onComplete)
        {
            LoadDataHelper<Config>("Config.json", v =>
            {
                config = v;
                onComplete?.Invoke();
            });
        }

        private static void ClearConfigData()
        {
            config = null;
        }

        #endregion

 
 

        private static void LoadDataHelper<T>(string fileName, UnityAction<T> onComplete)
        {
            string fullName = Simulation.Framework.Helper.GetStreamingAssets() + "/Configs/" + fileName;
            SingleBehavior<ResManagerByNet>.getInstance().LoadJson(fullName, json => {
                T cache = JsonToObj<T>(json);
                onComplete?.Invoke(cache);
            });
        }

        private static T JsonToObj<T>(string json)
        {
            try
            {
                return LitJson.JsonMapper.ToObject<T>(json);
            }
            catch
            {
                Log.Warning("json 转换 obj 有误>>" + json);
                return default(T);
            }
        }

        private delegate void LoadDataHandler(UnityAction onComplete);
    }
}